﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace weigh
{
    /**
     * 扫描码验证
     */
    public class CodeOperation
    {
        // 扫描码

        // 商户标识                         |商户姓名&农户标识                    |农户姓名
        // 8b115bf1731a436a8393461b9300e2e6|张三&412dbff1d23342719a7083b0ba66a383|李四
        private string txt;

        // 标识长度 32
        private const int SHOP_FLAG_LENGTH = 0x20;
        public CodeOperation(string txt)
        {
            this.txt = txt;
        }

        // 验证
        public bool check(out CodeStruct codeStorage)
        {
            codeStorage = default;

            if ( this.txt.Length < 65 )
            {
                Console.WriteLine("扫码长度不够");
                return false;
            }

            string txt = this.txt.Trim();


            // 正确结果应是 |
            string splitFlag = txt.Substring(SHOP_FLAG_LENGTH, 1);


            if (!splitFlag.Equals("|"))
            {
                return false;
            }

           

            int flagPosition = txt.IndexOf('&');

            if (-1 == flagPosition)
            {
                Console.WriteLine("没有&符号");
                return false;
            }

            string lastSplitFlag = txt.Substring(flagPosition + SHOP_FLAG_LENGTH + 1, 1);

            if (!lastSplitFlag.Equals("|"))
            {
                Console.WriteLine("没有第二个|符号");
                return false;
            }

          
            // 最后一个竖线
            int lastVerticalLine = flagPosition + SHOP_FLAG_LENGTH + 1;

            // 获取商、农户姓名

            string frammerName = txt.Substring(lastVerticalLine + 1);

            // 在 & 与 | 之间
            string shopName = txt.Substring(SHOP_FLAG_LENGTH + 1, flagPosition - SHOP_FLAG_LENGTH - 1);

            codeStorage = new CodeStruct();

            codeStorage.mid = txt.Substring(0, SHOP_FLAG_LENGTH);

            codeStorage.uid = txt.Substring(flagPosition + 1, SHOP_FLAG_LENGTH);

            codeStorage.frammerName = frammerName;

            codeStorage.shopName = shopName;

            return true;
        }
    }
}
